package com.lance.answer.gui.answer.gk.answer.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.CompleteInfo;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.answer.AnswerDTO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

@Slf4j
public class DoDaZuoYeTask extends Thread {


    private final String driverPath;
    private final LinkedBlockingDeque<AnswerDTO> answerDTOS;

    public DoDaZuoYeTask(String driverPath, LinkedBlockingDeque<AnswerDTO> answerDTOS) {
        this.driverPath = driverPath;
        this.answerDTOS = answerDTOS;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (answerDTOS.size() > 0) {
            AnswerDTO answerDTO = answerDTOS.take();
            String userName = answerDTO.getUsername();
            String password = answerDTO.getPwd();
            log.info("任务：{} 剩余 {} 行 用户名：{} 密码：{}",
                    Thread.currentThread().getName(), answerDTOS.size(), userName, password);
            run(answerDTO.getSubjectName(), driverPath, userName, password);
            //todo
        }

        if (answerDTOS.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }


    // 管理学基础 2065001457555 19940419
    public static void run(String subjectName, String driverPath, String userName, String password) throws Exception {

        String filePath = "libs//answerInfo//" + subjectName;
        //  String filePath = "D:\\project\\answer-tool\\libs\\answerInfo\\" + subjectName;

        if (!new File(filePath).exists()) {
            new File(filePath).mkdirs();
        }

        filePath = filePath + "//" + userName + "-upload.txt";

        File completeInfoFile = new File(filePath);
        if (!completeInfoFile.exists()) {
            completeInfoFile.createNewFile();
        }
        InputStream inputStream = new FileInputStream(completeInfoFile);
        String completeInfoStr = IOUtils.toString(inputStream, "UTF-8");
        List<CompleteInfo> completeInfoList = JSONObject.parseArray(completeInfoStr, CompleteInfo.class);
        if (null == completeInfoList) {
            completeInfoList = Lists.newArrayList();
        }


        // 定义是否开启浏览器没有这门课程
        boolean isStartChrome = true;

        List<String> haveCompleteHomeWorkUrlSet = Lists.newArrayList();

        for (CompleteInfo info : completeInfoList) {
            if (info.isComplete()) {
                haveCompleteHomeWorkUrlSet.add(info.getHomeworkUrl());
            }
        }
//        if(haveCompleteHomeWorkUrlSet.size()>0&&urlTasks.contains(haveCompleteHomeWorkUrlSet.get(0))){
//            isStartChrome = false;
//        }

        if (!isStartChrome) {
            return;
        }


        WebDriver driver = Util.getDriver(driverPath);
        //String url = "http://student.ouchn.cn/";
        String url = "http://passport.ouchn.cn/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dstudentspace%26redirect_uri%3Dhttp%253A%252F%252Fstudent.ouchn.cn%252F%2523%252Fsignin-oidc%2523%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520ouchnuser%2520ouchnstudentspaceapi%2520offline_access%26state%3Dca1cb5d0270b49fdaea508b8a846c457%26nonce%3Dd257df51b0a141ac8ed35b1caf59ef4c";
        driver.get(url);
        Thread.sleep(3000);
        //Util.login(driver, "2065001457555", "19940419");
        Util.login(driver, userName, password);
        Util.switchToFirst(driver);
        Thread.sleep(3000);

        boolean isFindSubject = false;

        for (WebElement we : driver.findElements(By.className("media-body"))) {
            Util.switchToFirst(driver);
            // 找到管理学基础
            String mediaTitle = we.findElement(By.className("media-title")).getText();

            if (!mediaTitle.equals(subjectName)) {
                continue;
            }
            isFindSubject = true;
            //点击进入学习的按钮
            WebElement studyButton = we.findElement(By.cssSelector("button[class='btn bg-primary']"));
            studyButton.click();
            //Util.switchToLast(driver);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (!isFindSubject) {
            try {
                driver.close();
                driver.quit();
            } catch (Exception e) {

            }
            return;
        }


        Util.switchToLast(driver);
        String viewUrl = driver.getCurrentUrl();
        System.err.println("viewUrl:" + viewUrl);

        viewUrl = viewUrl + "&test=1";
        driver.get(viewUrl);

        Thread.sleep(5000);


        Map<String, String> mapUrl = Maps.newHashMap();

        for (WebElement we : new WebDriverWait(driver, Duration.ofSeconds(20)).until((ExpectedCondition<List<WebElement>>)
                d -> d.findElements(By.className("test")))) {

            ///     WebElement testNameWe = Util.findByClassName(we,"pull-right");
            WebElement testNameWe = Util.findByTagName(we, "p");

            if (testNameWe == null) {
                continue;
            }
            System.err.println("?????????????+" + testNameWe.getText());
            String testName = testNameWe.getText();
            if (Strings.isNullOrEmpty(testName)) {
                continue;
            }
            if (!testName.contains("大作业") && !testName.contains("学习行为表现") && !testName.contains("社会实践")) {
                continue;
            }
            System.err.println("testName:" + testName);


            for (WebElement aTag : Util.findAllByTagName(we, "a")) {
                String href = aTag.getAttribute("href");
                System.err.println("href:" + href);
                if (Strings.isNullOrEmpty(href) || href.contains("quiz")) {
                    continue;
                }
                if (!href.contains("assign")) {
                    continue;
                }
                if ("进入形考".equals(aTag.getText())) {
                    mapUrl.put(href, testName);
                }
            }
        }

        System.err.println("msp:" + JSON.toJSONString(mapUrl));


        int i = 1;
        for (String urlTask : mapUrl.keySet()) {

                Util.switchToLast(driver);
                // FIXME 当完成第一份形考任务时，必须提交，否则会弹出 ”是否保存当前页面“消息
                driver.get(urlTask);
                Thread.sleep(2 * 1000);
                // 点击继续作业
                boolean isGoOn = true;
                for (WebElement we : driver.findElements(By.tagName("td"))) {
                    if (we.getText().equals("已提交请评分")) {
                        CompleteInfo completeInfo = new CompleteInfo();
                        completeInfo.setComplete(true);
                        completeInfo.setHomeworkUrl(urlTask);
                        completeInfoList.add(completeInfo);
                        Thread.sleep(2000);
                        isGoOn = false;
                    }
                    if (we.getText().equals("草稿（未提交）")) {

                        try {
                            for (WebElement we1 : driver.findElements(By.cssSelector("*[class='btn btn-secondary']"))) {
                                System.err.println("???" + we.getText());
                                if (we1.getText().trim().equals("提交作业")) {
                                    we.click();
                                    Thread.sleep(2000);
                                    driver.findElement(By.id("id_submissionstatement")).click();
                                    Thread.sleep(1000);
                                    driver.findElement(By.id("id_submitbutton")).click();
                                    Thread.sleep(5000);
                                    break;
                                }
                            }

                        } catch (Exception e) {

                        }
                        isGoOn = false;
                    }
                }
                if (!isGoOn) {
                    i++;
                    continue;
                }

                // form-check


                driver.findElement(By.cssSelector("*[class='btn btn-secondary']")).click();
                Thread.sleep(2000);

                WebElement element = driver.findElement(By.tagName("iframe"));
                System.out.println(element.toString());
                driver.switchTo().frame(element);
                WebElement webElement = driver.findElement(By.tagName("body"));
                InputStream inputStream2 = new FileInputStream(new File("F:\\国开WORD\\"+subjectName + "\\" + mapUrl.get(urlTask) + ".txt"));
                StringBuilder sb = new StringBuilder();
                for(String s:IOUtils.readLines(inputStream2,"UTF-8")){
                    sb.append(s);
                }
                String answer = sb.toString();
                //answer = new String(answer.getBytes(),"utf-8");
                if (null != webElement) {
                    webElement.clear();
                    webElement.sendKeys(answer);
                }
                //切换回主页面
                driver.switchTo().defaultContent();

                Thread.sleep(2000);
                driver.findElement(By.id("id_submitbutton")).click();


                //回到试题首页
                TimeUnit.SECONDS.sleep(2);



            }

        try {
            TimeUnit.SECONDS.sleep(2);
            // 将新的完成作业的信息更新进去
            FileUtils.write(completeInfoFile, JSONObject.toJSONString(completeInfoList, SerializerFeature.PrettyFormat), "utf-8");
            driver.close();
            driver.quit();
        } catch (Exception e111) {
            e111.printStackTrace();
        }




    }
}
